<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\AreaModel;
use app\common\model\Config;
use app\common\model\Goods;
use app\common\model\OfflineOrder;
use app\common\model\PointsLog;
use app\common\model\Shop;
use app\common\model\ShopGoods;
use app\common\model\ShopPlatformGoods;
use app\common\model\VisitLog;
use EasyAdmin\upload\Uploadfile;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\facade\Db;
use think\Validate;

class Home extends BaseController
{
    public function Home()
    {
        $user_id = $this->request->uid;
        $userInfo = $this->request->user_info;
        //首页信息
//        $data['logo'] = Config::where('name', '项目logo')->value('value') ?: "";

        //首页快捷应用图标显示 判断标识
        $data['flag'] = (int)Config::getSelfConfig('首页显示快捷方式');
        //上次浏览记录
        $shopList = VisitLog::where('user_id', $user_id)->group('shop_id')->order('id', 'desc')->limit(3)->field('max(id) as id')->select()->toArray();
//        dd($shopList);
        if ($shopList) {
            $data['shop'] = VisitLog::with('shop.district')->where('id', 'in', array_column($shopList, 'id'))->order('id', 'desc')->select() ?: [];
        } else {
            $data['shop'] = [];
        }

        //处理用户线下支付获取的积分
        if ($userInfo->unionid) {
            $orderList = OfflineOrder::where('unionid', $userInfo->unionid)->where('pay_status', 1)->where('send_status', 0)->select();

            //修改订单状态
            foreach ($orderList as $order) {
                Db::startTrans();
                try {
                    if ($order->points > 0) {
                        //给用户发放积分
                        //添加记录
                        Shop::where('id', $order->shop_id)->dec('points_one', $order->points)->update();
                        //用户收款信息
                        PointsLog::create([
                            'form_user_id'   => 0,
                            'user_id'        => $user_id,
                            'shop_id'        => $order->shop_id,
                            'num'            => $order->points,
                            'type'           => 1,
                            'flag'           => 1,
                            'relation_id'    => $order->id,
                            'relation_sheet' => 2,
                            'expire_time'    => time() + Config::getSelfConfig('积分有效时长'),
                        ]);
                    }
                    $order->send_status = 1;
                    $order->save();

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                }
            }
        }
        //积分总数
        $data['total_points'] = (new PointsLog())->getUsefulPoints($user_id);
        //生成收款码
//        $qr_code         = (new \Wechat())->getUnlimitQRCode('', '?userId=' . $user_id);
//        $data['qr_code'] = 'data:image/jpg;base64,' . base64_encode($qr_code);
        return success($data);
    }

    /**
     * 搜索
     */
    public function search()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'type|类型'        => 'require|number',  //1:商家 2:商品
            'key_words|关键词' => 'require',
            'shop_id|店铺id'   => 'requireIf:type,2',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }

        if ($param['type'] == 2) {
            $shop_id = $param['shop_id'];
            //获取店铺平台产品id列表
            $ids = ShopGoods::where('shop_id', $shop_id)->where('status', 1)->column('goods_id');
            $data = Goods::where('name', 'like', '%' . $param['key_words'] . '%')->where(function ($query) use ($shop_id, $ids) {
                $query->where('shop_id', $shop_id);
                if ($ids) {
                    $query = $query->whereOr('id', 'in', $ids);
                }
            })->limit(15)
                ->select();
        } else {
            $data = Shop::where('shop_code|name', 'like', '%' . $param['key_words'] . '%')->where('status', 1);
            if (input('district_id', 0)) {
                $data = $data->where('district_id', input('district_id'));
            }
            $data = $data->select();
        }
        return success($data);
    }


    /**
     *  获取省市区
     */
    public function getAreaList()
    {
        // 实现思路:
        // 数据全部拿出来,然后做下遍历
        // 最后存缓存
        $key = "area_list";
        if (!cache('?' . $key)) {
            $list = AreaModel::where('status', 1)
                ->order('pid', 'desc')
                ->order('level', 'desc')
                ->column('id,pid,name,shortname,level', 'id');
            foreach ($list as $k => $v) {
                if ($v['pid'] == 0) {
                    continue;
                }
                if (isset($list[$v['pid']])) {
                    $list[$v['pid']]['children'][] = $list[$k];
                }
                unset($list[$k]);
            }
            cache($key, array_values($list));
        }
        return success(cache($key));
    }

    /**
     * 上传图片
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'                    => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        try {
            $this->validate($data, $rule);
        } catch (\Exception $e) {
            if ($e->getCode() == 0) {
                return error('图片尺寸过大');
            }
            return error($e->getMessage());
        }

        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return success(['img' => $upload['url']]);
        }
        return error($upload['msg']);
    }

    /**
     * 用户的获取店铺积分列表
     * 就是首页 点击 总积分 跳转新的页面上 展现 用户在每家店铺有多少积分
     * 0824
     */
    public function userShopPointList()
    {
        //获取分页信息
        $param = $this->request->param();
        $param['page_size'] = 6;
        [$pageSize, $page] = paginate($param);
        //获取用户id
        $userId = $this->request->uid;
        //获取用户所有积分都是哪些店铺发放的
        $shopIdList = PointsLog::where('user_id', $userId)
            ->where('type', 1)
            ->where('flag', 1)
            ->column('shop_id');
        //获取店铺信息
        $shop = Shop::where('id', 'in', $shopIdList)->select();
        //循环获取用户在每家店铺中有多少可使用积分
        foreach ($shop as &$v) {
            //如果当前店铺 在商圈或者连锁中
            if ($v->district_id) {
                $shopIdList = \app\common\model\Shop::where('district_id', $v->district_id)->column('id');
                $shopIdList = array_values($shopIdList);
            } else {
                $shopIdList = array_values([$v->id]);
            }
            //获取当前店铺可使用积分
            $v['available_points'] = (new PointsLog())->getUsefulPoints($userId, $shopIdList);
        }
        //返回输出
        return success($shop);
    }
}